const { app, BrowserWindow, ipcMain } = require('electron');
const { join } = require("path");
const { promisify } = require("util");
const { readFile, writeFile } = require("fs");
let main_window = null;
const create_window = async (path = "./config.json") => {
  let Browser_window = {
    width: 900,
    height: 675,
    x: null,
    y: null
  };
  try {
    let res = await promisify(readFile)(path, "utf8");
    Browser_window = JSON.parse(res);
  } catch (err) {
    console.error(err);
  } finally {
    main_window = new BrowserWindow({
      ...Browser_window,
      "useContentSize": true,
      "minHeight": 400,
      "minWidth": 300,
      // "alwaysOnTop": true,
      "frame": false,
      // 当拖拽放大窗口时，防止出现黑边，同时双击不能缩小了。
      // "transparent": true,
      "backgroundColor": "#fff",
      "webPreferences": {
        "nodeIntegration": true,
        "contextIsolation": false
      }
    });
    // 消除警告
    process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
    // 加载页面
    main_window.loadFile("./index/index.html");
    // 打开调试面板
    // main_window.webContents.openDevTools();
  };
};
ipcMain.on("win", (event, type) => {
  switch (type) {
    case "minimize":
      main_window.minimize();
      break;
    case "colse":
      // 获取窗口的大小和位置
      let [width, height] = main_window.getSize();
      let [x, y] = main_window.getPosition();
      // 当关闭窗口时，记录窗口的大小和位置
      writeFile("./config.json", JSON.stringify({ x, y, width, height }), () => {
        main_window.close();
      });
      break;
    case "fullScreen":
      main_window.isFullScreen() ? main_window.setFullScreen(false) : main_window.setFullScreen(true);
      break;
    case "max":
      main_window.isMaximized() ? main_window.restore() : main_window.maximize();
      break;
    default: break;
  };
});
app.whenReady().then(() => {
  create_window();
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) create_window();
  });
});
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
    main_window = null;
  };
});